﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace Remote_server
{
    /// <summary>
    /// Contains some utlity methods that may be
    /// used by windows, controls and similar
    /// </summary>
    static class WindowUtilities
    {
        /// <summary>
        /// Force a TextBox to allow only digits
        /// </summary>
        /// <param name="txt">The TextBox instance</param>
        public static void AllowOnlyDigits(this TextBox txt)
        {
            AllowOnly(txt, s => IsDigit(s));
        }

        /// <summary>
        /// Force a TextBox to allow only certain strings,
        /// this method controls keydown, textinput and pasting events
        /// </summary>
        /// <param name="txt">The TextBox instance</param>
        /// <param name="predicate">A Predicate that tells
        /// whether a certain string is allowed</param>
        public static void AllowOnly(this TextBox txt, Predicate<string> predicate)
        {
            txt.PreviewKeyDown += (o, e) =>
            {
                try
                {
                    char c = e.Key == Key.Space ? ' ' : char.Parse(e.Key.ToString());
                    if (!predicate(c.ToString()))
                        e.Handled = true;
                }
                catch { }
            };
            txt.PreviewTextInput += (o, e) =>
            {
                if (!predicate(e.Text))
                    e.Handled = true;
            };
            DataObject.AddPastingHandler(txt, new DataObjectPastingEventHandler(
                (o, e) =>
                {
                    bool interrupt = true;
                    if (e.DataObject.GetDataPresent(DataFormats.Text))
                    {
                        string s = (string)e.DataObject.GetData(DataFormats.Text);
                        if (!predicate(s))
                            interrupt = false;
                    }
                    if (interrupt)
                        e.CancelCommand();
                }));
        }

        /// <summary>
        /// Check whether a string is a digit
        /// </summary>
        /// <param name="text">The string to test</param>
        /// <returns>True if the string contains only digits,
        /// false otherwise</returns>
        public static bool IsDigit(string text)
        {
            foreach (char c in text)
                if (!char.IsDigit(c))
                    return false;
            return true;
        }
    }
}
